// 主要游戏逻辑文件

// 定义画布和上下文变量
var can1;
var can2;
var ctx1;
var ctx2;

// 定义画布尺寸变量
var canWidth = 820;
var canHeight = 640;
var maxHeight = window.innerHeight;
var maxWidth = window.innerWidth;

// 定义游戏状态变量
var beginGame;
var gameOver;

// 定义游戏对象变量
var backrgound;
var squares;
var mySquare;
var beginAnim;

// 定义时间相关变量
var lastTime;
var changeColorTime;
var changeTimeArrays = ["10", "9", "8", "7", "6", "5", "4", "3", "2", "1", "color change!"];
var changeColorindex = 0;

// 定义游戏速度和分数变量
var totalSpeed = 3;
var score;
var highScore = localStorage.getItem('highScore') || 0;

// 页面加载完成后调用game函数
document.body.onload = game;

// 游戏初始化函数
function game() {
    init();
    loop = setInterval(gameloop, 20);
}

// 初始化游戏参数和对象
function init() {
    // 初始化分数、游戏状态等变量
    score = 0;
    beginGame = false;
    gameOver = false;
    
    // 记录上一帧的时间
    lastTime = Date.now();
    
    // 获取画布元素并设置上下文
    can1 = document.getElementById("myCanvas1");
    ctx1 = can1.getContext("2d");
    can2 = document.getElementById("myCanvas2");
    ctx2 = can2.getContext("2d");
    
    // 动态调整画布大小以适应窗口
    if (maxWidth != canWidth) {
        canWidth = maxWidth;
    }
    if (maxHeight != canHeight) {
        canHeight = maxHeight;
    }
    document.getElementById("main_box").style.width = canWidth + 'px';
    document.getElementById("main_box").style.height = canHeight + 'px';
    
    can1.width = canWidth;
    can2.width = canWidth;
    can1.height = canHeight;
    can2.height = canHeight;
    
    // 隐藏游戏标题和得分，显示开始按钮
    document.getElementById("game_title").style.display = "none";
    document.getElementById("login_btn").style.display = "block";
    document.getElementById("score").style.display = "none";
    
    // 初始化颜色变化时间提示框样式
    colorChangeTimeW = (canHeight > canWidth ? canWidth : canHeight) * 0.5;
    document.getElementById("colorChangeTime_div").style.width = colorChangeTimeW * 1.6 + "px";
    document.getElementById("colorChangeTime_div").style.height = colorChangeTimeW * 0.5 + "px";
    document.getElementById("colorChangeTime_div").style.marginLeft = -colorChangeTimeW * 0.8 + "px";
    document.getElementById("colorChangeTime_div").style.lineHeight = colorChangeTimeW * 0.5 + "px";
    document.getElementById("colorChangeTime_div").style.fontSize = colorChangeTimeW * 0.3 + "px";
    
    // 初始化背景、方块和玩家对象
    backrgound = new backgroundObj();
    backrgound.init();
    
    squares = new squareObj();
    squares.init();
    
    mySquare = new mySquareObj();
    mySquare.init();
    
    beginAnim = new beginAnimObj();
    beginAnim.init();
    
    // 替换 jQuery 点击事件，绑定开始游戏的点击事件
    document.getElementById("login_btn").addEventListener("click", function() {
        loginGame();
    });
}

// 重启游戏，重置所有游戏对象和参数
function restart() {
    backrgound.init();
    squares.init();
    mySquare.init();
    lastTime = Date.now();
    document.getElementById("state").style.display = "none";
    document.getElementById("game_title").style.display = "none";
    document.getElementById("login_btn").style.display = "none";
    document.getElementById("score").style.display = "block";
    score = 0;
    totalSpeed = 3;
}

// 游戏主循环，更新游戏状态并绘制画面
function gameloop() {
    // 绘制背景
    backrgound.draw();
    
    // 清除画布并保存当前状态
    ctx2.clearRect(0, 0, canWidth, canHeight);
    ctx2.save();
    
    // 如果开始动画处于活动状态，绘制开始动画
    if (beginAnim.isLive && Date.now() - lastTime > 1000) {
        beginAnim.draw();
    }
    
    // 如果游戏开始且未结束，更新游戏状态和绘制游戏元素
    if (beginGame && !gameOver) {    
        // 确保得分始终显示并更新得分
        document.getElementById("score").style.display = "block";
        document.getElementById("score").innerHTML = "得分:" + Math.floor(score);
        
        // 判断得分是否超过最高记录，超过则改为红色并显示提示
        if (score > highScore) {
            document.getElementById("score").style.color = "red";
            localStorage.setItem('highScore', score);
            
            // 显示"新纪录"提示
            var congratsDiv = document.getElementById("congrats_hint");
            if (!congratsDiv && !hasShownCongrats) {
                congratsDiv = document.createElement("div");
                congratsDiv.id = "congrats_hint";
                congratsDiv.style.position = "absolute";
                congratsDiv.style.top = "50%";
                congratsDiv.style.left = "50%";
                congratsDiv.style.transform = "translate(-50%, -50%)";
                congratsDiv.style.fontSize = "30px";
                congratsDiv.style.color = "gold";
                congratsDiv.style.fontWeight = "bold";
                congratsDiv.style.textShadow = "2px 2px 4px rgba(0, 0, 0, 0.5)";
                congratsDiv.innerHTML = "新纪录！";
                document.getElementById("main_box").appendChild(congratsDiv);
                
                // 设置提示在2秒后消失
                setTimeout(function() {
                    var congratsHint = document.getElementById("congrats_hint");
                    if (congratsHint) {
                        congratsHint.parentNode.removeChild(congratsHint);
                    }
                }, 2000);
                
                hasShownCongrats = true;
            }
        } else {
            document.getElementById("score").style.color = "black";
        }
        
        // 增加速度并绘制方块和玩家
        addSpeed();
        squares.draw();
        mySquare.draw();
        squaresToMy();
        
        // 绑定点击事件以触发玩家跳跃
        document.getElementById("main_box").addEventListener("click", function() {
            mySquare.jump();
        });
    } else if (gameOver && !beginGame) {
        // 添加玩法提示
        var playHintDiv = document.createElement("div");
        playHintDiv.id = "play_hint";
        playHintDiv.style.position = "absolute";
        playHintDiv.style.top = "20%";
        playHintDiv.style.left = "50%";
        playHintDiv.style.transform = "translate(-50%, -50%)";
        playHintDiv.style.fontSize = "20px";
        playHintDiv.style.color = "white";
        playHintDiv.style.fontWeight = "bold";
        playHintDiv.style.textShadow = "2px 2px 4px rgba(0, 0, 0, 0.5)";
        playHintDiv.innerHTML = "点击屏幕或按空格键跳跃";
        document.getElementById("main_box").appendChild(playHintDiv);
        
        // 设置玩法提示在3秒后消失
        setTimeout(function() {
            var playHint = document.getElementById("play_hint");
            if (playHint) {
                playHint.parentNode.removeChild(playHint);
            }
        }, 3000);
    }
    ctx2.restore();
}

// 开始游戏函数
function loginGame() {
    changeColorTime = Date.now();
    document.getElementById("colorChangeTime_div").style.display = "block";
    document.getElementById("colorChangeTime_div").style.color = squareColor[Math.floor(Math.random() * squareColor.length)];
    document.getElementById("colorChangeTime_div").innerHTML = changeTimeArrays[changeColorindex];
    if (!gameOver && !beginGame) {
        document.getElementById("score").style.display = "block";
        document.getElementById("game_title").style.display = "none";
        document.getElementById("square_main").style.display = "none";
        beginGame = true;
        document.getElementById("login_btn").style.display = "none";
    } else if (gameOver && !beginGame) {
        restart();
        gameOver = false;
        beginGame = true;
    }
    beginAnim.isLive = false;
    document.getElementById("square_main").style.display = "none";
}

// 增加游戏速度和分数
function addSpeed() {
    totalSpeed += 0.04 * 0.05;
    score += 0.04;
}

// 处理方块与玩家的碰撞
function squaresToMy() {
    for (var i = 0; i < squares.num; i++) {
        if (squares.isLive[i]) {
            if (squares.color[i] != mySquare.color) {
                if (mySquare.isLive) {
                    // 检查碰撞条件并更新玩家状态
                    if (((mySquare.x + mySquare.l - 1 > squares.x[i] && mySquare.x + mySquare.l - 1 < squares.x[i] + squares.w[i]
                        && mySquare.x + mySquare.l - 30 > squares.x[i] && mySquare.x + mySquare.l - 30 < squares.x[i] + squares.w[i])
                        || (mySquare.x > squares.x[i] && mySquare.x + 10 < squares.x[i] + squares.w[i]
                        && mySquare.x + 10 > squares.x[i] && mySquare.x + 10 < squares.x[i] + squares.w[i]))
                        && (mySquare.y + mySquare.l > squares.y[i] && mySquare.y + mySquare.l < squares.y[i] + squares.h[i])) {
                        mySquare.y = squares.y[i] - mySquare.l;
                        mySquare.toVSpeed = -totalSpeed * 0.2;
                        mySquare.toDownSpeed = 0;
                        jump_count = 0;
                    }
                    if (mySquare.x + mySquare.l > squares.x[i] && mySquare.x + mySquare.l < squares.x[i] + squares.w[i]
                        && mySquare.y + mySquare.l > squares.y[i] && mySquare.y + mySquare.l < squares.y[i] + squares.h[i]) {
                        mySquare.x = squares.x[i] - mySquare.l;
                    }            
                }
            }    
        }
    }
}

// 定义暂停标志变量
var isPaused = false;

// 监听键盘事件
document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        // 切换暂停状态
        isPaused = !isPaused;
        if (isPaused) {
            clearInterval(loop);
            document.getElementById("pause_hint").style.display = "block";
        } else {
            loop = setInterval(gameloop, 20);
            document.getElementById("pause_hint").style.display = "block"; // 修改为常驻显示
        }
    }
    // 新增：监听空格键按下事件
    if (event.key === ' ' || event.code === 'Space') {
        mySquare.jump(); // 触发方块跳跃
    }
});

// 新增：添加标志变量，用于跟踪是否已显示过“新纪录”提示
var hasShownCongrats = false;